package configs

import (
	"flag"
	"fmt"
	"github.com/spf13/viper"
	"log"
)

var appConfPathDefault = "configs/resource/application.properties"
var databaseConfPathDefault = "configs/resource/database.properties"

type AppConfInfo struct {
	ServerPort string
}

type DBConfInfo struct {
	MaxIdleConns int
	MaxOpenConns int
	DriveName    string
	ShowSQL      bool

	AppSourceName string
	//CommonDBSourceName string
}

var DBConfig DBConfInfo
var AppConfig AppConfInfo

func InitConf() {
	//从命令行中获取配置文件路径
	var appConfPath string
	var databaseConfPath string

	//在program arguements 中配置参数，格式 -appConfPath "xxx" -databaseConfPath "yyy"
	flag.StringVar(&appConfPath, "appConfPath", appConfPathDefault, "应用程序配置文件路径")
	flag.StringVar(&databaseConfPath, "databaseConfPath", databaseConfPathDefault, "数据库配置文件路径")

	fmt.Println("appConfPath:", appConfPath)
	fmt.Println("databaseConfPath:", databaseConfPath)

	//解析命令行参数写入注册的flag里
	flag.Parse()

	//1、初始化app配置 viper读取配置文件application.properties
	viper.SetConfigFile(appConfPath)
	if err := viper.ReadInConfig(); err != nil {
		log.Fatal("配置文件未找到！")
	}
	AppConfig.ServerPort = viper.GetString("server.port")
	log.Println("端口：", AppConfig.ServerPort)

	//2、viper读取配置文件database.properties
	viperDB := viper.New()
	viperDB.SetConfigType("properties")
	viperDB.SetConfigFile(databaseConfPath)
	if err := viperDB.ReadInConfig(); err != nil {
		log.Fatal("数据库配置文件未找到！")
	}
	//c := viperDB.AllSettings() //获取所有配置
	//log.Println("所有配置：", c)

	//初始化DB配置
	DBConfig.DriveName = viperDB.GetString("database.driveName")
	DBConfig.ShowSQL = viperDB.GetBool("database.showSQL")
	DBConfig.MaxIdleConns = viperDB.GetInt("database.maxIdleConns")
	DBConfig.MaxOpenConns = viperDB.GetInt("dataBase.maxOpenConns")
	DBConfig.AppSourceName = viperDB.GetString("app.database.sourceName")

	log.Println(fmt.Sprintf("初始化完成：\n  DBConfig.DriveName: %v\n  DBConfig.ShowSQL: %v\n  "+
		"DBConfig.MaxIdleConns:%v\n  DBConfig.MaxOpenConns:%v\n  DBConfig.AppSourceName: %v\n", DBConfig.DriveName,
		DBConfig.ShowSQL, DBConfig.MaxIdleConns, DBConfig.MaxOpenConns, DBConfig.AppSourceName))

}
